<template>
  <qx-table :option="tableOption" :remoteData="remoteData">
    <template v-slot:top>
      <qx-form v-model="searchForm" :option="tableOption" isSearch @submit="startSearch"></qx-form>
    </template>
    <template v-slot:topRight="{ row = {} }">
      <div class="text-bold relative-position">
        <q-badge :color="getColorByValue(row.shelfTypStyle, rackFixedTypes, {}, 'grey-4')"
                 class="q-badge-dot absolute-badge-dot" rounded></q-badge>
        <span class="q-ml-md">
          {{ getLabelByValue(row.shelfTypStyle, rackFixedTypes, {}, $t('Misc.NonFixed')) }}
        </span>
      </div>
    </template>
    <template v-slot:menuLeft>
      <q-btn outline text-color="primary" @click="handleSync('headoffice', $t('Misc.SynchronousHeadquarters'))">
        {{ $t('Misc.SynchronousHeadquarters') }}
      </q-btn>
      <q-btn outline text-color="primary" @click="handleSync('rcs', $t('Misc.SynchronizeRCSData'))">
        {{ $t('Misc.SynchronizeRCSData') }}
      </q-btn>
      <q-btn outline text-color="primary" @click="handleSync('toRcs', $t('Misc.SynchronizeToRCS'))">
        {{ $t('Misc.SynchronizeToRCS') }}
      </q-btn>
    </template>
    <template v-slot:Image="{ row }">
      <div class="full-width row justify-center">
        <CarrierIMG :carrierType="row.shelfType" :imageUrl="row.floorPlanPath"
                    classes="col-6 q-ma-sm cursor-pointer cursor-hover-image rounded-borders"
                    @click="handleModelInfo(row)"></CarrierIMG>
        <div class="column full-width items-center text-dark text-weight-medium text-body1">
          <div>{{ `${row.shelfTypeNo}_${row.shelfTypeName}` }}</div>
          <div v-if="row.isFixed === '0'">
            {{ `${row.shelfLength || 0}x${row.shelfWidth || 0}mm ${row.shelfWeight || 0}kg` }}
          </div>
          <div v-if="row.isFixed === '1'">
            {{ `${row.shelfLength || 0}x${row.shelfWidth || 0}mm` }}
          </div>
        </div>
        <div class="full-width text-caption row no-wrap justify-between items-center q-gutter-sm q-pt-sm">
          <q-badge v-if="row.rotateDeviceNames" class="col q-ml-none" color="primary" outline>
            <q-icon class="q-mr-xs" name="rotate_left" size="1.05rem"></q-icon>
            <div class="ellipsis">{{ row.rotateDeviceNames || '' }}</div>
            <q-tooltip v-bind="$tooltipAttr">
              {{ `${$t('AGVCore.RotatableAGVModel')}: ${row.rotateDeviceNames || ''}` }}
            </q-tooltip>
          </q-badge>
          <q-badge v-if="row.shortSideDeviceNames" class="col" color="primary" outline>
            <q-icon class="q-mr-xs" name="mdi-import" size="1.05rem"></q-icon>
            <div class="ellipsis">{{ row.shortSideDeviceNames || '' }}</div>
            <q-tooltip v-bind="$tooltipAttr">
              {{ `${$t('AGVCore.ShortSideEntryAGVModel')}: ${row.shortSideDeviceNames || ''}` }}
            </q-tooltip>
          </q-badge>
        </div>
      </div>
    </template>
    <template v-slot:menu="{ row }">
      <q-btn class="col" color="primary" outline unelevated @click="handleBinding(row)">
        {{ $t('AGVCore.BindingAGVModel') }}
      </q-btn>
    </template>
  </qx-table>
  <q-modal v-model="syncVisible" :header="header" width="400" @beforeClose="beforeClose" @confirm="submitSync">
    <qx-form ref="FormRef" v-model="formInfo" :option="syncOption" class="q-pr-md"></qx-form>
  </q-modal>
  <q-modal v-model="bindingModelVisible" :header="$t('AGVCore.BindingAGVModel')" width="450" @beforeClose="beforeClose"
           @confirm="submitBind">
    <qx-form ref="FormRef" v-model="formInfo" :option="tableOption" class="q-pr-md"></qx-form>
  </q-modal>
  <RackTypeInfo v-model="modalVisible" :rowInfo="formInfo" :storageSlotInfo="storageSlotInfo"></RackTypeInfo>
</template>
<script setup>
import { i18n, toI18nName } from 'boot/i18n.js'
import { postAPI } from 'src/api/index.js'
import { getRemoteData, setRemoteData } from 'src/enum/ajaxRemoteData.js'
import CarrierIMG from 'src/views/CarrierCore/CarrierIMG.vue'
import { rackCategory, rackFixedTypes } from 'src/views/CarrierCore/enum.js'
import RackTypeInfo from 'src/views/CarrierCore/RackTypeInfo.vue'
import { computed, onMounted, ref } from 'vue'
import { createDialog, deepClone, getColorByValue, getLabelByValue } from 'src/utils/utils.js'

const header = ref('')
const formInfo = ref({})
const FormRef = ref(null)
const AGVBrands = ref([])
const AGVModels = ref([])
const searchForm = ref({})
const syncVisible = ref(false)
const storageSlotInfo = ref({})
const modalVisible = ref(false)
const bindingModelVisible = ref(false)
const remoteData = ref({ dicUrl: '/yfagv/api/agvMasDataShelfBase/list' })
getRemoteData('agv_model', '/yfagv/api/agvTypeDevice/list').then(data => (AGVModels.value = data))
getRemoteData('agv_brand', '/yfagv/api/agvCfgBrand/list').then(data => (AGVBrands.value = data))
const syncOption = computed(() => {
  return {
    span: 22, labelWidth: 90,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      props: { label: `${toI18nName('agvBrandNameZhCn')}`, value: 'agvBrandCode' }, required: true
    }]
  }
})
const tableOption = computed(() => {
  return {
    grid: true, searchSpan: 5, export: true, span: 23,
    column: [{
      label: `${i18n.t('CarrierCore.RackType')}`, field: 'shelfTypeName', minWidth: 100, hide: true,
      readonly: true, format: (_, row) => `${row.shelfTypeNo}_${row.shelfTypeName}`
    }, {
      label: `${i18n.t('CarrierCore.RackCategory')}`, field: 'shelfType', type: 'select', options: rackCategory.value,
      minWidth: 100, readonly: true, topLeft: true
    }, {
      label: '', field: 'Image', slot: true, export: false, minWidth: 100, search: false, nonHeader: true,
      display: false, showInfo: false
    }, {
      label: `${i18n.t('Misc.FixedType')}`, field: 'shelfTypStyle', type: 'select', options: rackFixedTypes.value,
      display: false, search: false, minWidth: 80, hide: true
    }, {
      label: `${i18n.t('CarrierCore.RackParams')}`, field: 'rackParam', minWidth: 100, hide: true, search: false,
      format: (_, row) => {
        if (row.isFixed === '1') return `${row.shelfLength || 0}x${row.shelfWidth || 0}mm`
        return `${row.shelfLength || 0}x${row.shelfWidth || 0}mm ${row.shelfWeight || 0}kg`
      }, readonly: true
    }, {
      label: `${i18n.t('AGVCore.RotatableAGVModel')}`, field: 'rotateDeviceIds', type: 'select', minWidth: 100,
      options: AGVModels.value, props: { label: 'agvBrandCode, deviceName', value: 'id' }, hide: true, search: false,
      format: (_, row) => row.rotateDeviceNames
    }, {
      label: `${i18n.t('AGVCore.ShortSideEntryAGVModel')}`, field: 'shortSideDeviceIds', type: 'select', minWidth: 100,
      options: AGVModels.value, props: { label: 'agvBrandCode, deviceName', value: 'id' }, hide: true, search: false,
      format: (_, row) => row.shortSideDeviceNames
    }, {
      label: `${i18n.t('CreationTime')}`, field: 'createdTime', search: false, minWidth: 80, hide: true, display: false
    }]
  }
})

const handleModelInfo = row => {
  formInfo.value = row
  modalVisible.value = true
  storageSlotInfo.value = {}
  postAPI('yfagv/api/agvMasDataShelfType/agvMasDataShelfType', { id: row.id }, data => {
    const { east = [], middle = [], north = [], south = [], west = [] } = data
    storageSlotInfo.value = { east, middle, north, south, west }
  })
}
const handleSync = (source, title) => {
  if (source === 'headoffice') {
    createDialog({ msg: `${i18n.t('Misc.SyncTip3')}` }, () => {
      postAPI('/yfagv/api/syncAgvCfg/syncAgvMasDataShelfType', {}, () => startSearch('clear'))
    })
    return
  }
  header.value = title
  formInfo.value = { source }
  const msg = source === 'rcs' ? `${i18n.t('Misc.SyncTip1')}` : `${i18n.t('Misc.SyncTip2')}`
  createDialog({ msg }, () => {
    syncVisible.value = true
  }, () => {})
}
const handleBinding = row => {
  formInfo.value = deepClone(row)
  if (row.isFixed === '1') formInfo.value.rackParam = `${row.shelfLength || 0}x${row.shelfWidth || 0}mm`
  else formInfo.value.rackParam = `${row.shelfLength || 0}x${row.shelfWidth || 0}mm ${row.shelfWeight || 0}kg`
  bindingModelVisible.value = true
}
const formatSearchForm = () => ({ ...searchForm.value })
const startSearch = (action, done) => {
  remoteData.value.params = formatSearchForm()
  remoteData.value.clearSelected = true
  if (done) done()
  action === 'clear' && setRemoteData('rack_type')
}
const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  syncVisible.value = false
  bindingModelVisible.value = false
}
const submitSync = mDone => {
  FormRef.value.validate((form, done) => {
    const uri = form.source === 'rcs' ? '/yfagv/api/syncRcsToFactoryApi/syncAgvMasDataShelfType'
      : '/yfagv/api/syncRcsApi/syncRcsAgvMasDataShelfType'
    postAPI(uri, form, () => {
      startSearch(form.source === 'rcs' ? 'clear' : '')
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}

const submitBind = mDone => {
  FormRef.value.validate((form, done) => {
    let name = ''
    if (!form.rotateDeviceIds) name = i18n.t('AGVCore.RotatableAGVModel')
    if (form.shortSideDeviceIds) name =
      name ? `${name}、${i18n.t('AGVCore.ShortSideEntryAGVModel')}` : i18n.t('AGVCore.ShortSideEntryAGVModel')
    if (!name) return ajaxBind(done, mDone)
    createDialog({ msg: i18n.t('Misc.EmptyTips', { name }) }, () => ajaxBind(done, mDone), () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}

const ajaxBind = (done, mDone) => {
  postAPI('/yfagv/api/agvMasDataShelfBase/saveShelfTypeDeviceType', formInfo.value, () => {
    startSearch()
    done()
    mDone && mDone()
  }, () => {
    done()
    mDone && mDone(false)
  })
}

onMounted(startSearch)
</script>